package com.eleadmin.gzh.controller;


import com.eleadmin.damon.utils.utils.HttpsUtils;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.system.entity.User;
import com.eleadmin.gzh.service.Wxservice;
import com.eleadmin.gzh.utils.AesException;
import com.eleadmin.gzh.utils.WXPublicConstants;
import com.eleadmin.gzh.utils.WXPublicUtils;
import com.eleadmin.order.service.CustomerService2313;
import com.eleadmin.order.service.DriverService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Map;

/**
 * api登录相关接口
 * Created by lining on 2019-05-29 下午 3:43.
 * http://localhost/swagger-ui.html
 * http://192.168.1.110/swagger-ui.html
 */
@RequestMapping("/api/nt/gzh")
@RestController
@Api(value = "登录Api", tags = {"登录Api"})
public class GzhNtController extends BaseController {

    //    @Qualifier("jdbcTokenStore")
//    @Autowired
//    private TokenStore tokenStore;
    @Autowired
    private CustomerService2313 customerService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private Wxservice wxservice;

    /**
     * 微信公众平台token
     * 服务器地址(URL)  本地用        http://5rayz9.natappfree.cc/api/nt/login/gzh
     * 服务器地址(URL)  正式服务器用   http://gzh.sszgjzx.com
     */
    @ApiOperation(value = "微信公众平台token", notes = "" +
            "signature 公众号加密签名\n" +
            "timestamp 公众号时间戳\n" +
            "nonce 公众号随机数字\n" +
            "echostr 公众号随机字符串\n" +
            "", httpMethod = "GET")
    @GetMapping("/login")
    public String gzhValidate(String signature, String timestamp,
                              String nonce, String echostr) throws AesException {
        if (WXPublicUtils.verifyUrl(signature, timestamp, nonce)) {
            System.out.println("公众号验证成功!");
            return echostr;
        }
        return null;
    }

    @PostMapping(value = "login")
    public void processMsg(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 调用核心服务类接收处理请求
        Map<String, String> requestMap = wxservice.parseRequest(request.getInputStream());
        System.out.println(requestMap);
        //准备回复的数据包
        String resXml = wxservice.getRespose(requestMap);
//                "<xml>" +
//                "<ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName>" +
//                "<FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName>" +
//                "<CreateTime>"+ System.currentTimeMillis()/1000 +"</CreateTime>" +
//                "<MsgType><![CDATA[text]]></MsgType>" +
//                "<Content><![CDATA[why?]]></Content>" +
//                "</xml>";

        PrintWriter out = response.getWriter();
        System.out.println(resXml);
        out.print(resXml);
        out.flush();
        out.close();
//        ServletInputStream is = request.getInputStream();
//        byte[] b = new byte[1024];
//        int len;
//        StringBuilder sb = new StringBuilder();
//        while ((len=is.read(b))!=-1) {
//            sb.append(new String(b, 0, len));
//        }
    }


//    /**
//     * 得到保存绑定用户二维码的ticket
//     */
//    @PostMapping(value = "getUserLoginTicket")
//    public String getUserLoginTicket(String params) throws IOException, DocumentException {
//        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+ GzhToken.getAccessToken();
//        //生成临时字符串二维码 expire_seconds 单位秒
//        //{"scene_str": "customerId=12;customerName=中盈"}
//        String data = "{\"expire_seconds\": 2000, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+params+"\"}}}";
//        String post = HttpsUtils.post(url, data);
//        String ticket = JSONObject.fromObject(post).getString("ticket");
//        return ticket;
//    }



    @GetMapping(value = "getGzhOauth")
    public void getGzhOauth(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String path = WXPublicConstants.GZH_LOGIN_URL+"/api/nt/wx/getGzhCode";

        path = URLEncoder.encode(path, "UTF-8");
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+
                WXPublicConstants.APPID +"&redirect_uri="
                + path
                + "&response_type=code&scope=snsapi_base#wechat_redirect";
        response.sendRedirect(url);
    }


    @GetMapping(value = "getGzhCode")
    public void getGzhCode(HttpServletRequest request, HttpServletResponse response) {
        String code = request.getParameter("code");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        url = url.replace("APPID", WXPublicConstants.APPID).replace("SECRET", WXPublicConstants.APPSECRET)
                .replace("CODE", code);
        String ret = null;
        ret = HttpsUtils.get2(url);
//    System.out.println(ret);

        JSONObject obj = JSONObject.fromObject(ret);
//    String at = obj.getString("access_token");
//    String openid = obj.getString("openid");
//    url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//    url = url.replace("ACCESS_TOKEN",at).replace("OPENID",openid);
//    ret = HttpsUtils.get2(url);
//    JSONObject obj = JSONObject.fromObject(ret);
        login(obj, request, response);
    }

    public void login(JSONObject obj, HttpServletRequest request, HttpServletResponse response) {
        User user = new User();
        user.setGzhId(obj.getString("openid"));
//    try {
//      user = userService.getByGzhId(user);
//    } catch (EmptyResultDataAccessException e) {
//    }
////    user.setNickname(obj.getString("nickname"));
//      user.setSex(1);
////    user.setCity(obj.getString("city"));
////    user.setProvince(obj.getString("province"));
////    user.setCountry(obj.getString("country"));
////    user.setAvatar(obj.getString("headimgurl"));
//
//    if (user.getUserId() != null) {
//      userService.update2(user);
//    } else {
//      // 添加到数据库
//      List<Integer> roleids = new ArrayList<>();
//      roleids.add(WXPublicConstants.NORMAL_USER);
//      //新增的用户都为普通游客
//      user.setRoleIds(roleids);
//      user.setUsername(System.currentTimeMillis()+"");
//      user.setPassword(UserConstant.DEFAULT_PSW);
//      userService.save2(user);
//    }
//    String access_token = JwtUtil.buildToken(user.getUsername(), Constants.TOKEN_EXPIRE_TIME, Constants.TOKEN_KEY);
//    // 记录登录日志
//    loginRecordService.saveAsync(user.getUsername(), 0, "", request);
//
//    String url = "http://"+WXPublicConstants.GZH_URL+"?access_token="+access_token;
//    try {
//      response.sendRedirect(url);
//    } catch (IOException e) {
//    }
//    return JsonResult.ok("登录成功").put("access_token", access_token);
//    .put("openId", obj.getString("openid")).put("userinfo", user)
    }


}
